package com.jiuyou.websocket.config;

import com.jiuyou.websocket.handler.TalkMessageHandler;
import com.jiuyou.websocket.interceptor.WebSocketInterceptor;
import com.jiuyou.websocket.manager.WebSocketSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

/**
 * websocket配置类
 */

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private TalkMessageHandler talkMessageHandler;

    @Autowired
    private WebSocketInterceptor webSocketInterceptor;

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

    /**
     * 注册WebSocketHandler处理器
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry
                //WebSocket处理器
                .addHandler(talkMessageHandler, "/ws/connect/talk")
                //WebSocket拦截器
                .addInterceptors(webSocketInterceptor)
                //处理跨域请求
                .setAllowedOrigins("*");
    }

    /**
     * 由spring管理WebSocketSession管理器
     */
    @Bean
    public WebSocketSessionManager webSocketSessionManager(){
        return new WebSocketSessionManager();
    }

}
